<template>
    <div class="productdetail">
        <div class="back" @click="onClickLeft">
            <van-icon name="arrow-left" />
        </div>
        <van-swipe class="my-swipe" :autoplay="3000" lazy-render>
            <van-swipe-item v-for="image in data.pics" :key="image">
                <img :src="image" />
            </van-swipe-item></van-swipe>
        <div class="mid">
            <!-- <span v-if="sukDataPreOrder.price">
                ￥{{ sukDataPreOrder.price }}
            </span> -->
            <span>
                <!-- ￥421.99 -->
                ￥{{ data.member_price }}
            </span>
            <!-- <span>百草味零食大礼包卤味礼盒送礼物猪肉办公室夜宵食品</span> -->
            <span>{{ data.name }}</span>
        </div>
        <div class="btm">
            <div class="tit">
                <span class="icon"></span>
                商品详情
            </div>
            <div class="intro">
                <!-- <span>{{ data.intro }}</span> -->
                <span v-html="data.goods_detail"></span>
            </div>
            <!-- <van-image fit="cover" :src=" data.image" /> -->
        </div>
        <van-action-bar>
            <van-action-bar-icon icon="star-o" v-if="!star" @click="star = 1" text="收藏" color="#212121" />
            <van-action-bar-icon icon="star" @click="star = 0" v-else text="已收藏" color="#0A81FA" />
            <!-- <van-action-bar-icon icon="share-o" text="分享" color="#212121" /> -->
            <van-action-bar-button type="warning" text="加入购物车" @click="onClickIcon" />
            <van-action-bar-button type="danger" text="立即购买" @click="onClickButton" />
        </van-action-bar>

    </div>
    <van-popup v-model:show="show" closeable position="bottom" round :style="{ height: '56%' }">
        <div class="con">
            <div class="card">
                <div class="shopImg">
                    <!-- <img style="width: 100%;height: 100%;"
                        :src="data.image"
                        alt=""> -->
                    <van-image fit="cover" :src="data.image" />
                </div>
                <div class="pre">
                    <div class="shopT">
                        {{ data.name }}
                    </div>
                    <div class="shopP"></div>
                    <div class="shopPrice" :style="gradientTextStyle">
                        <span>￥</span>
                        {{ sukDataPreOrder.price || 0 }}
                    </div>
                </div>
            </div>
            <van-cell-group v-for="attrs in sukData" :key="attrs.id" :title="attrs.name" :border="false">
                <van-button v-for="item in attrs.sons" :key="item.id"
                    :class="{ 'active': isSelected(attrs.id, item.id) }" @click="selectAttr(attrs.id, item.id)">
                    {{ item.name }}</van-button>
            </van-cell-group>

            <!-- <van-cell-group title="规格2" :border="false">
                <van-button>主要按钮</van-button>
                <van-button>主要按钮</van-button>
            </van-cell-group> -->
            <div class="num">
                <div class="tit">购买数量</div>
                <van-stepper v-model="purchaseNum" theme="round" button-size="22" disable-input />
            </div>
        </div>
    </van-popup>
</template>

<script lang="ts">
import { useRoute, useRouter } from "vue-router";
import { productInfo, productSku, preOrder, ProductcartCreate } from '../../../api/index';
import { onMounted, ref, computed, reactive, watch } from 'vue';
import { Toast } from 'vant';

export default {
    setup() {
        const route: any = useRoute();
        const data = ref("");
        const star = ref(0);
        const purchaseNum = ref(1);
        const sukData = ref([]);
        const selectedAttrs = ref([]);
        const sukDataPreOrder = ref({
            id: "",
            product_id: "",
            attrs: "",
            price: "",
            stock: 0
        });
        const clickNum = ref(0)
        const router = useRouter();

        let formData = new FormData();

        // 初始化selectedAttrs状态，假设每个属性组的第一个属性项默认被选中
        // const selectedAttrs = ref(
        //     sukData.value.map(group => ({
        //         id: group.id,
        //         selected: group.sons[0].id // 默认选中第一个属性项
        //     }))
        // );
        // selectAttr方法的实现
        const selectAttr = (groupId, itemId) => {
            // groupId是属性组的id，itemId是属性项的id
            const groupIndex = selectedAttrs.value.findIndex(group => group.id === groupId);

            if (groupIndex === -1) {
                // 如果没有找到对应的属性组，创建一个新的
                selectedAttrs.value.push({ id: groupId, selected: itemId });
            } else {
                // 如果找到了，更新该组的选中项
                selectedAttrs.value[groupIndex].selected = itemId;
            }
        };
        // 辅助方法，用于检查某个属性项是否被选中
        const isSelected = (groupId, itemId) => {
            const group = selectedAttrs.value.find(group => group.id === groupId);
            return group ? group.selected === itemId : false;
        };
        // 格式化selectedAttrs为"id1:itemId1,id2:itemId2"的格式
        const formatSelectedAttrs = () => {
            let pairs = selectedAttrs.value.map(group => `${group.id}:${group.selected}`);
            return pairs.join(",");
        };
        const onClickLeft = () => history.back();
        const onClickIcon = () => {
            show.value = true;
            clickNum.value++;
            if (clickNum.value > 1) {
                formData = new FormData();
                formData.append("number", purchaseNum.value)
                formData.append("sku_id", sukDataPreOrder.value?.id)
                ProductcartCreate(formData).then(res => {
                    if (res.code == 1) {
                        // console.log(res.data)
                        Toast(res.msg)
                        show.value = false;
                    } else {
                        Toast(res.msg)
                    }
                })
                formData = new FormData();
            }
        };
        const onClickButton = () => {
            show.value = true;
            clickNum.value++;
            if (clickNum.value > 1) {
                let str: string = `sku_id:${sukDataPreOrder.value?.id || ""},number:${purchaseNum.value}`

                formData.append("data", str);
                // console.log(formData)
                preOrder(formData).then(res => {
                    if (res.code == 1) {
                        console.log(res.data)
                        // Toast(res.msg)
                        router.push({
                            path: "/home/qrdd/" + res.data,
                            // name: "qrdd",
                            state: { id: res.data }
                        });
                    } else {
                        Toast(res.msg)
                    }
                })

                formData = new FormData();
            }
        };
        const show = ref(false);
        onMounted(() => {
            productInfo(route.params.id).then(res => {
                console.log(res.data)
                data.value = res.data
                sukData.value = res.data.attrs
                // 初始化selectedAttrs
                selectedAttrs.value = res.data.attrs.map((group) => ({
                    id: group.id,
                    selected: group.sons[0].id,
                }));
            })
        })
        // 监听selectedAttrs的变化
        watch(
            () => selectedAttrs.value,
            (newValue, oldValue) => {
                // 每次selectedAttrs变化时，重新格式化数据
                const formattedData = formatSelectedAttrs();
                // 重置formData并添加新的数据
                formData = new FormData();
                formData.append("id", data.value.id);
                formData.append("sku", formattedData); // 假设服务器端接收的字段是sku

                // 调用productSku接口
                productSku(data.value.id, formattedData, formData).then(res => {
                    if (res.code == 1) {
                        console.log(res.data);
                        sukDataPreOrder.value = res.data;
                    } else {
                        sukDataPreOrder.value = {
                            id: "",
                            product_id: "",
                            attrs: "",
                            price: "",
                            stock: 0
                        };
                        Toast(res.msg)
                    }
                });
                formData = new FormData();
            },
            { deep: true }, // 开启深度监听
        );
        watch(
            () => show.value,
            (newValue, oldValue) => {
                if (newValue == false) {
                    clickNum.value = 0
                }
            },
        );

        const gradientTextStyle = ref({
            background: '-webkit-linear-gradient(49.56276305112369deg, #EB4A4A 0%, #EA7A7A 100%)',
            '-webkit-background-clip': 'text',
            '-webkit-text-fill-color': 'transparent',
            'font-weight': 'bold',
            'font-size': '18px',
            'margin-top': '5px'
        });
        return {
            data, onClickLeft, onClickIcon, onClickButton, star, show,
            purchaseNum, sukData, selectedAttrs,
            selectAttr,
            isSelected, sukDataPreOrder,
            gradientTextStyle
        };
    },
}
</script>

<style lang="less" scoped>
.productdetail {
    width: 100vw;
    height: 100%;
    background: #F6F7F9;
    position: relative;
}

.back {
    position: absolute;
    top: 50px;
    left: 15px;
    z-index: 99999;
    background: #878888;
    height: 30px;
    width: 30px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;

    .van-icon {
        font-size: 16px;
        color: #fff;
    }
}

.my-swipe .van-swipe-item {
    text-align: center;
    width: 100%;
    height: 311px;
}

.mid {
    margin: 20px 15px;
    height: 99px;
    background: #FFFFFF;
    border-radius: 12px 12px 12px 12px;
    display: flex;
    flex-direction: column;
    padding: 10px 20px;
    justify-content: space-between;
    box-sizing: border-box;

    span {
        font-size: 16px;
        color: #232323;
        text-align: left;

        &:nth-child(1) {
            font-weight: 700;
            font-size: 24px;
            color: #E1222A;
            // margin-bottom: 8px;
        }
    }
}

.btm {
    box-sizing: border-box;
    margin: 0 15px;
    height: 299px;
    background: #FFFFFF;
    border-radius: 12px 12px 12px 12px;
    padding: 16px 20px;
    margin-bottom: 50px;

    .tit {
        font-size: 16px;
        color: #3D3D3D;
        text-align: left;
        display: flex;
        align-items: center;

        .icon {
            display: inline-block;
            width: 5px;
            height: 16px;
            background: linear-gradient(143deg, #FF4546 5%, #FF6991 100%);
            border-radius: 347px 347px 347px 347px;
            margin-right: 12px;
        }
    }

    .intro {
        width: 100%;
        margin: 26px auto 13px;
        font-size: 14px;
        color: #232323;
        text-align: left;
    }


    .van-image,
    .van-image__img {
        width: 100%;
        height: 200px;
        border-radius: 6px 6px 6px 6px;
    }

    :deep(.van-image__img) {
        width: 100%;
        height: 100%;
        border-radius: 6px 6px 6px 6px;
    }
}

.van-action-bar {
    z-index: 9999;
}

.num {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;

    .tit {
        font-size: 14px;
        color: #3D3D3D;
    }

    .van-stepper {
        margin-right: 15px;

        :deep(.van-stepper__plus) {
            background-color: #0A82FB;
        }

        :deep(.van-stepper__minus) {
            border-color: #0A84FF;
            color: #0A84FF;
        }
    }
}
</style>
<style lang="less" scoped>
.con {
    padding: 30px 15px;

    .card {
        display: flex;
        margin-top: 5px;
        margin-bottom: 22px;

        .shopImg,
        .van-image {
            width: 80px;
            height: 60px;
            border-radius: 3px 3px 3px 3px;

        }

        .pre {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            justify-content: space-around;
            margin: 0 7px;

            .shopT {
                flex: 1;
                font-weight: 700;
                font-size: 12px;
                color: #343434;
                margin-top: -5px;
            }

            .shopP {
                flex: 1;
                font-size: 11px;
                color: #666666;
            }

            .shopPrice {
                flex: 1;

                span {
                    font-size: 12px;
                }

                // margin-top: 5px;
                // font-weight: 700;
                // font-size: 18px;
                /* 根据需要设置字体大小 */
                background: -webkit-linear-gradient(49.56276305112369deg, #EB4A4A 0%, #EA7A7A 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                background-clip: text;
                color: transparent;
                /* 确保在不支持-webkit-text-fill-color的浏览器中文字不可见 */
            }
        }
    }

    :deep(.van-cell-group) {
        display: flex;
        justify-content: flex-start;

        .van-button {
            width: 73px;
            height: 30px;
            background: #F8F9FC;

            border-radius: 347px 347px 347px 347px;
            font-size: 14px;
            color: #232323;
            white-space: nowrap;
            margin: 15px 17px 15px 0;

            // &:nth-child(1) {
            //     background: linear-gradient(143deg, #0A84FF 0%, #0A7EF3 100%);
            //     color: #FFFFFF;
            // }
        }

        .active {
            background: linear-gradient(143deg, #0A84FF 0%, #0A7EF3 100%);
            color: #FFFFFF;
        }
    }

}


:deep(.van-cell-group__title) {
    font-size: 14px;
    color: #3D3D3D;
    text-align: left;
    padding: 0;
}
</style>